import {_decorator, Component, instantiate, Node, Prefab, resources} from 'cc';
import {EventManager} from "db://assets/Scripts/Common/EventManager";
import {EventType} from "db://assets/Scripts/Common/EventType";
import {ModelPath} from "db://assets/Scripts/Common/ModelPath";
import {PoolManager} from "db://assets/Scripts/framework/PoolManager";

const {ccclass, property} = _decorator;

/**
 * 管理所有玩家
 */
@ccclass('PlayerManager')
export class PlayerManager extends Component {
    /**
     * 玩家预制体
     */
    private playerPrefab: Prefab = null;

    onLoad() {
        this.initPlayerPrefab();
    }

    onEnable() {
        // 注册创建玩家事件
        EventManager.on(EventType.CREATE_PLAYER, this.onCreatePlayer, this);
    }

    onDisable() {
        // 取消注册创建玩家事件
        EventManager.off(EventType.CREATE_PLAYER, this.onCreatePlayer, this);
    }

    start() {

    }

    update(deltaTime: number) {

    }

    /**
     * 初始化玩家预制体
     */
    private initPlayerPrefab() {
        resources.load(ModelPath.player, Prefab, (err, data) => {
            if (err) {
                console.error("PlayerManager：玩家模型加载失败！");
                return;
            }
            // 设置玩家预制体
            this.playerPrefab = data;
        });
    }

    /**
     * 创建玩家
     */
    private onCreatePlayer() {
        if (!this.playerPrefab) {
            this.initPlayerPrefab();
            return;
        }

        // 实例化预制体
        const playerNode: Node = instantiate(this.playerPrefab);
        // 设置父节点
        playerNode.setParent(this.node);
        // const playerNode: Node = PoolManager.getInstance().getNode(this.playerPrefab, this.node);
        // 设置位置
        playerNode.setPosition(0, 0, 7);

        // 重新开始游戏
        EventManager.emit(EventType.RESTART);
    }
}